package org.winexpress

import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;
import grails.converters.JSON

/**
 *
 * @author Swee Zhi
 */


class WineTypeManagement {
    
    def listWineTypes() {
        def wineTypes = WineType.list()
        JSONArray arr = new JSONArray()
        wineTypes.each() {
            JSONObject obj = new JSONObject()
            obj.put("id",it.id)
            obj.put("typeName",it.typeName)
            obj.put("description",it.description)
            arr.add(obj)
        }
        
        return arr
    }
    
    def getWineTypeByID(id) {
        def wineType = WineType.findById(id)
        JSONObject obj = new JSONObject()
        obj.put("id",wineType.id)
        obj.put("typeName",wineType.typeName)
        obj.put("description",wineType.description)
        
        return obj
    }
    
    def getWineTypeByTypeName(typeName) {
        def wt = WineType.findByTypeName(typeName)
        JSONObject obj = new JSONObject()
        obj.put("id",wt.id)
        obj.put("typeName",wt.typeName)
        obj.put("description",wt.description)
        
        return obj
    }

    def getWineTypeForDbByTypeName(typeName) {
        def wt = WineType.findByTypeName(typeName)
        
        return wt
    }
    
    def addWineType(o) {
        def status
        
        WineType wt = new WineType()
        wt.typeName = o.get("typeName")
        wt.description = o.get("description")
        if (wt.save()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Add Wine >> ' + status
        
        return status
    }
    
    def updateWineType(wineType) {
        def status
        
        WineType wt = WineType.findById(wineType.id)
        if (wineType.has("typeName")) { wt.typeName = wineType.typeName }
        if (wineType.has("description")) { wt.description = wineType.description }
        if (wt.save(flush:true)) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Update Wine >> ' + status
        
        return status
    }
    
    def deleteWineType(id) {
        def status
        
        WineType wt = WineType.findById(id)
        if (wt.delete()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Delete Wine >> ' + status
        
        return status
    }
    
}

